<template>
	<view class="msg">
		<top-header is-show-back @get-size="getSize">
			<view class="header">
				<view v-for="tab in tabList" :key="tab.key" class="tab" :class="{
					active: activeKey === tab.key
				}" @click="handleTab(tab.key)">{{tab.label}}</view>
			</view>
		</top-header>
		<view class="bg" :style="{
			paddingTop: `calc(${barHeight}px + 24rpx)`,
			// height: `calc(${barHeight}px + 24rpx)`
		}" />
		<view class="container" :class="{
			grey: !isShowFollow,
		}" :style="{
			paddingTop: `calc(${barHeight}px + 24rpx)`
		}">

			<view v-if="list && list.length" class="tip">
				<template v-if="isShowFollow">
					关注了{{total}}家公司
				</template>
				<template v-if="!isShowFollow">{{total}}条动态未查看</template>
			</view>
			<empty v-else></empty>
			<template v-if="isShowFollow">
				<view v-for="follow in list" :key="follow.enterpriseId" class="follow-item">
					<view class="follow-lf">
						<view class="follow-cnt">{{ follow.enterpriseName }}</view>
						<view class="follow-time">{{ follow.followTime }}</view>
					</view>
					<view class="follow-btn" @click="handleCancelFollow(follow)">
						<view v-if="followCache[follow.enterpriseId]" class="follow-icon">
							<uni-icons type="back" color="#fff" size="18"></uni-icons>
						</view>
						<text v-else>已关注</text>
					</view>
				</view>
			</template>
			<template v-if="!isShowFollow">
				<view v-for="(news, nIndex) in list" :key="news.id" class="news-item"
					@click="handleDetail(news, nIndex)">
					<view class="news-cnt">
						<view class="news-row">
							<view class="news-label">公司名称：</view>
							<view class="news-val">{{ news.title || ''}}</view>
						</view>
						<view class="news-row">
							<view class="news-label">更新类型：</view>
							<view class="news-val">{{news.changeType && Action_Change[news.changeType] || ''}}</view>
						</view>
						<view class="news-row">
							<view class="news-label">内容详情：</view>
							<view class="news-val">{{ showCnt(news.message) }}</view>
						</view>
					</view>
					<view class="news-time" :class="{
						flg: news.readStatus === 0
					}">
						时间：{{news.createTime || ''}}
					</view>
				</view>
			</template>
		</view>
	</view>
</template>

<script>
	import topHeader from '@/components/topHeader.vue'
	import {
		getFollowListApi,
		getActionListApi,
		changeFollowApi
	} from '@/api/follow.js'
	import {
		Action_Change
	} from './constant.js'
	import {
		H5_APP_ID,
		APP_ID
	} from "@/config/app.js";
	export default {
		components: {
			topHeader
		},
		data() {
			return {
				tabList: [{
						key: 'follow',
						label: '关注'
					},
					{
						key: 'action',
						label: '动态'
					}
				],
				barHeight: 44,
				activeKey: 'action',
				list: [],
				pageNum: 1,
				totalPage: 0,
				pageSize: 10,
				total: 0,
				followCache: {},
				Action_Change,
				readIndex: -1 // 阅读索引
			}
		},
		computed: {
			isShowFollow() {
				return this.activeKey === 'follow'
			}
		},
		onLoad({
			type
		}) {
			const validType = ['follow', 'action'].includes(type)
			this.activeKey = validType ? type : 'follow'
			this.getList()

			// 监听阅读动态
			uni.$on('Read_Action', () => {
				const index = this.readIndex
				index >= 0 && this.list.splice(index, 1, {
					...this.list[index],
					readStatus: 1
				})
				this.readIndex = -1
			})
		},
		beforeDestroy() {
			uni.$off('Read_Action')
		},
		methods: {
			// 内容详情展示
			showCnt(cnt) {
				const length = cnt.length
				let text = ''
				let suffix = ` ${length} 条信息更新`
				const len = 36 - suffix.length
				let num = 0
				for (let i = 0; i < length; i++) {
					const itm = cnt[i]
					if (text.length + itm.length + !!(i !== length - 1) < len) {
						text += itm + '、'
					} else {
						break
					}
					num++
				}
				return text.replace(/、+$/g, '') + (num < length ? '等' : '') + suffix
			},
			// 获取顶部导航高度
			getSize({
				top,
				height
			}) {
				this.barHeight = top + height
			},
			// 切换tab
			handleTab(key) {
				this.activeKey = key
				this.resetQuery()
			},
			// 跳转动态详情
			handleDetail({
				enterpriseId,
				title,
				changeType,
				createTime,
				batchNumber,
				id,
				readStatus
			}, index) {
				this.readIndex = index
				uni.navigateTo({
					url: decodeURIComponent(
						`/pagesUser/msg/detail?enterpriseId=${enterpriseId}&batchNumber=${batchNumber}&changeType=${changeType}&companyName=${title}&createTime=${createTime}&${readStatus === 0 ? `id=${id}` : ''}`
					),
				})
			},
			// 重置列表查询
			resetQuery() {
				this.list = []
				this.pageNum = 1;
				this.total = 0
				this.totalPage = 0
				this.getList()
			},
			// 获取列表数据
			async getList() {
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}
				const res = this.isShowFollow ? await getFollowListApi({
					...params,
					type: 'follow'
				}) : await getActionListApi({
					...params,
					msgType: 0, // 消息类型 0-系统消息
					eventType: 'enterprise_change' // 事件类型 企业变更
				})

				const {
					totalPage,
					list = [],
					total
				} = res?.data || {}
				this.totalPage = totalPage || 0
				this.total = total || 0
				const appendList = this.isShowFollow ? list : list.map(item => {
					let obj
					try {
						obj = JSON.parse(item.objectContent)
					} catch {
						obj = {}
					}
					return {
						...item,
						...obj,
						message: item.message.split('、')
					}
				})
				this.list.push(...appendList)

				// 未查看动态数获取
				if (!this.isShowFollow) {
					const res = await getActionListApi({
						msgType: 0,
						eventType: 'enterprise_change',
						readStatus: 0, // 未读
					})
					this.total = res?.data?.total || 0
				}
			},
			// 取消关注
			async handleCancelFollow({
				enterpriseId
			}) {
				if (this.followCache[enterpriseId]) return
				this.$set(this.followCache, enterpriseId, true)
				try {
					await changeFollowApi({
						enterpriseId,
						action: 0,
						// #ifdef H5
						appId: H5_APP_ID,
						// #endif
						// #ifdef MP-WEIXIN
						appId: APP_ID,
						// #endif
					})
					this.$util.Tips(`取消关注成功！`);
					this.resetQuery()
				} finally {
					this.$delete(this.followCache, enterpriseId)
				}
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 0,
			});
			this.resetQuery()
			uni.stopPullDownRefresh();
		},
		// 上拉加载
		onReachBottom() {
			if (this.totalPage > this.pageNum) {
				this.pageNum++
				this.getList()
			} else {
				this.$util.Tips("没有更多数据了");
			}
		},
	}
</script>



<style lang="scss" scoped>
	.msg {

		::v-deep .empty-container {
			padding-top: 20vh;
		}

		.news-item {
			margin: 20rpx 30rpx;
			border-radius: 8rpx;
			background-color: #fff;

			.news-time {
				color: #999;
				font-size: 26rpx;
				line-height: 37rpx;
				padding: 29rpx 20rpx 28rpx 0;
				border-top: 2rpx solid #F5F5F5;
				text-align: right;

				&.flg {
					position: relative;

					&:before {
						content: '';
						position: absolute;
						left: 30rpx;
						top: 40rpx;
						width: 14rpx;
						height: 14rpx;
						border-radius: 100%;
						background-color: #FF0000;
					}
				}
			}

			.news-row {
				font-size: 28rpx;
				color: #666;
				line-height: 40rpx;
				margin-top: 25rpx;
				display: flex;
				letter-spacing: 0;
				font-family: monospace;

				.news-label {
					white-space: nowrap;
				}

				.news-val {
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}
			}

			.news-cnt {
				padding: 9rpx 20rpx 34rpx;
			}
		}

		.follow-item {
			padding: 12rpx 30rpx 14rpx 30rpx;
			display: flex;
			align-items: center;
			height: 160rpx;
			justify-content: space-between;
			position: relative;
			box-sizing: border-box;

			.follow-lf {
				flex: 1;
			}

			&::after {
				position: absolute;
				bottom: 0;
				left: 30rpx;
				right: 30rpx;
				height: 2rpx;
				content: '';
				background-color: #F5F5F5;

			}

			.follow-time {
				color: 28rpx;
				line-height: 40rpx;
				color: #999;
				margin-top: 4rpx;
			}

			@keyframes rotate {
				from {
					transform: rotate(0deg);
				}

				to {
					transform: rotate(360deg);
				}
			}

			.follow-btn {
				width: 140rpx;
				height: 58rpx;
				border-radius: 8rpx;
				background-color: #e6e6e6;
				color: #fff;
				font-size: 26rpx;
				line-height: 37rpx;
				text-align: center;
				padding-top: 10rpx;
				box-sizing: border-box;

				.follow-icon {
					animation: rotate 0.25s linear infinite;
				}
			}

			.follow-cnt {
				color: #000;
				font-weight: bold;
				font-size: 32rpx;
				line-height: 45rpx;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

		.header {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 34rpx;
			color: #fff;
		}

		.tab {
			padding: 0 35rpx;

			&.active {
				position: relative;

				&::after {
					content: '';
					width: 40rpx;
					height: 7rpx;
					border-radius: 4rpx;
					background-color: #fff;
					position: absolute;
					left: 50%;
					bottom: -7rpx;
					transform: translateX(-20rpx);
				}
			}
		}

		.container {

			min-height: 100vh;
			background-color: #fff;
			padding-bottom: 30rpx;
			box-sizing: border-box;

			&.grey {
				background-color: #FAF8F9;
			}
		}

		.bg {
			position: fixed;
			left: 0;
			right: 0;
			z-index: 10;
			background-color: #488AFD;
		}

		.tip {
			padding: 40rpx 0 14rpx 30rpx;
			font-size: 26rpx;
			line-height: 30rpx;
			color: #999;
			background-color: #FAF8F9;
		}
	}
</style>